<?php

class DoodleDAO
{
	private $conn;
	private $databaseSelected;
	
	
	function __construct()
	{
		$this->conn = mysql_connect();
        $this->databaseSelected = mysql_select_db(DB_NAME);
        
        if(!$this->conn || !$this->databaseSelected)
        {
            die('Database connection error in DoodleDAO');
        }
	}

	function abstractFromFile()
	{
	$handle = @fopen("/home/whitebox/public_html/g4d/abs.txt", "r");
	if ($handle)
		{
		while (!feof($handle)) 
			{
				$line = fgets($handle);
				$q = "INSERT INTO `googledoodle_dev`.`abstract` (`iddoodle` ,`pcode` ,`abstract`)VALUES".$line;
				$result = mysql_query($q, $this->conn);
				
				$msg = $result?"":"failed on ".$line;
				echo($msg."<br />");
			}
		fclose($handle);
		}
	}

	function findById($id)
	{
		$qry = '
				SELECT 
					*
				FROM 
					doodle
					INNER JOIN
					abstract
					ON
					doodle.iddoodle = abstract.iddoodle
				WHERE
					doodle.iddoodle = '.$id.'
				';
        $result = mysql_query($qry, $this->conn);
        if(!$result)
        {
            die('Could not retrieve doodle by id DoodleDAO');
        }
		$doodles = array();
		$row = mysql_fetch_array($result);
		$doodle= new Doodle($row['iddoodle'], "doodle name not stored", $row['abstract'], $row['image_filename'], $row['image_filename'], $row['iddoodle']);
        return $doodle;
	}
	
	function findAll()
	{
		$qry = '
				SELECT 
					*
				FROM 
					doodle
					INNER JOIN
					abstract
					ON
					doodle.iddoodle = abstract.iddoodle
				';
        $result = mysql_query($qry, $this->conn);
        if(!$result)
        {
            die('Could not retrieve doodle list in DoodleDAO');
        }
		$doodles = array();
		while($row = mysql_fetch_array($result))
		{
			$doodles[]= new Doodle($row['iddoodle'], "doodle name not stored", $row['abstract'], $row['image_filename'], $row['image_filename'], $row['iddoodle']);
		}
        return $doodles;
	}


	function findRandom($year = false, $group = false)
	{
		$where = "WHERE doodle.received = 'Yes' ";
		if($year)
		{
			$where .= " AND year_level='".$year."' ";
		}
		if($group)
		{
			if($group=="f")
			{
				$where .= " AND finalist320='Yes' ";
			}else{
				$where .= " AND finalist32='Yes' ";
			}
		}
		$qry = '
				SELECT 
					*
				FROM 
					doodle
					INNER JOIN
					abstract
					ON
					doodle.iddoodle = abstract.iddoodle
				'
				.$where.
				' 
				ORDER BY RAND()
				LIMIT 1
				';
        $result = mysql_query($qry, $this->conn);
        if(!$result)
        {
            die('Could not retrieve random doodle DoodleDAO');
        }
		$doodles = array();
		$row = mysql_fetch_array($result);
		$doodle= new Doodle($row['iddoodle'], "doodle name not stored", $row['abstract'], $row['image_filename'], $row['image_filename'], $row['iddoodle']);
        return $doodle;
     }
}
?>
